<?php
require_once '../config.php';   
require_once '../admin_check.php'; // 包含管理员验证

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        // 获取并验证用户ID
        $user_id = filter_input(INPUT_POST, 'user_id', FILTER_VALIDATE_INT);
        if (!$user_id || $user_id < 1) {
            throw new Exception("Invalid user ID");
        }

        // 禁止删除自己
        if ($user_id == $_SESSION['user_id']) {
            throw new Exception("Cannot delete your own account");
        }

        // 执行删除操作
        $stmt = $pdo->prepare("DELETE FROM users WHERE id = ?");
        $stmt->execute([$user_id]);

        if ($stmt->rowCount() > 0) {
            $_SESSION['success'] = "User deleted successfully";
        } else {
            $_SESSION['errors'] = ["User not found or already deleted"];
        }
    } catch (Exception $e) {
        $_SESSION['errors'] = [$e->getMessage()];
    }

    // 返回用户列表
    header('Location: index.php');
    exit;
} else {
    // 非POST请求直接跳转
    header('Location: index.php');
    exit;
}